package com.chuan.icons;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Douban extends SiteBase {
	Douban(FriendActivity context) {
		super(context);
		mSite = "douban";
	}

	public JSONArray getAccountInfo() {
		JSONArray ary = new JSONArray();
		ary.put("username");
		return ary;
	}

	@Override
	public Boolean getFriendsList(JSONObject info) {
		try {
			mUser = info.getString("user");
		} catch (JSONException e) {
			return false;
		}

		updateDiagInfo(R.string.str_fetch_account);

		String url = "http://api.douban.com/people/" + mUser
				+ "/contacts?alt=json";
		String buf = httpDownload(url);
		if (buf == null) {
			updateDiagInfo(R.string.str_http_error);
			return false;
		}

		JSONObject objs = null;
		JSONArray friends = null;
		try {
			objs = new JSONObject(buf);
			friends = objs.getJSONArray("entry");
		} catch (JSONException e) {
			updateDiagInfo(R.string.str_fetch_account_fail);
			return false;
		}

		String name, f_id, icon;
		JSONArray linkobj = null;
		for (int i = 0; i < friends.length(); ++i) {
			try {
				name = friends.getJSONObject(i).getJSONObject("title")
						.getString("$t");
				f_id = friends.getJSONObject(i).getJSONObject("db:uid")
						.getString("$t");

				linkobj = friends.getJSONObject(i).getJSONArray("link");
				icon = "";
				for (int j = 0; j < linkobj.length(); ++j) {
					if (linkobj.getJSONObject(j).getString("@rel").equals(
							"icon")) {
						icon = linkobj.getJSONObject(j).getString("@href");
					}
				}

				Log.d(Constants.LOG_FLAG, "Add friends." + f_id + name + icon);

				addFriends(f_id, name, icon);
			} catch (JSONException e) {
				continue;
			}
		}

		updateDiagInfo(R.string.str_fetch_account_success);
		return true;
	}

	@Override
	public Boolean pairFriends(JSONObject info) {
		return pairFriendsByName(info);
	}
}
